package com.big_data_studio.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.big_data_studio.entity.Role;
import com.big_data_studio.entity.user.User;
import com.big_data_studio.entity.user.UserDetailsModel;
import com.big_data_studio.mapper.UserMapper;
import com.big_data_studio.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiao_jie
 * @date 2022/10/2 20:11
 * @describe this is a text
 */

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("login_name", loginName));
        UserDetailsModel detailsModel = new UserDetailsModel();
        List<String> collect = roleService.listRolesByUserId(user.getId()).stream().map(Role::getRoleName).collect(Collectors.toList());
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String str :
                collect) {
            authorities.add(new SimpleGrantedAuthority(str));
        }
        detailsModel.setUser(user);
        detailsModel.setAuthorities(authorities);
        return detailsModel;
    }

}


